package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

var client = http.Client{
	Timeout: 3 * time.Second,
}

func NetCaseHandler(w http.ResponseWriter, r *http.Request) {
	Url := "https://www.163.com/robots.txt"
	resp, err := client.Get(Url)
	if err != nil {
		fmt.Printf("resp error: %v\n", err)
	}
	body := resp.Body
	defer body.Close() //一定要close，防止协程泄露
	res, err := ioutil.ReadAll(body)
	if err != nil {
		fmt.Printf("read error : %v\n", err)
	}
	fmt.Fprint(w, string(res))
}

type Error struct {
	Code    int64  `json:"code"`
	Message string `json:"message"`
	Result  bool   `json:"result"`
	Id      int64  `json:"id"`
}

type ResError struct {
	Error Error `json:"error"`
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	Index := ResError{Error: Error{
		Code:    4,
		Message: "method not found",
		Result:  false,
		Id:      0,
	}}
	Out, _ := json.Marshal(Index)
	fmt.Printf("=====host: %s\n", r.Host)
	fmt.Printf("=====RemoteAddr: %s\n", r.RemoteAddr)
	fmt.Printf("=====RequestURI: %s\n", r.RequestURI)
	fmt.Printf("=====method: %s\n", r.Method)
	fmt.Printf("=====header:\n")
	for k, v := range r.Header {
		fmt.Printf("%v: %v\n", k, v)
	}

	fmt.Println("=====cookie:")
	for _, cookie := range r.Cookies() {
		fmt.Printf(cookie.String() + "\n")
	}

	fmt.Printf("=====body:\n")
	io.Copy(os.Stdout, r.Body)
	fmt.Fprint(w, string(Out))
}

func main() {
	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/netcase", NetCaseHandler) //路由，请求对应路径时执行IndexHandler
	http.ListenAndServe(":5656", nil)           //不发生error会一直阻塞

}
